<template>
  <div>
    <!-- 下拉刷新 -->
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <!-- 上拉加载更多 -->
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :immediate-check="false"
      >
        <!-- 循环渲染文章的列表 -->
        <art-item
   v-for="item in artlist"
   :key="item.art_id.toString()"
   :article="item"
   @remove-article="removeArticle"
  >
</art-item>
      </van-list>
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh" :disabled="finished"></van-pull-refresh>
  </div>
</template>

<script>
import { getArtListAPI } from "../../api/home.API";
import ArtItem from "../ArtItem/ArtItem.vue";
export default {
  name: "ArtList",
  props: {
    // 频道 Id（小驼峰命名法：第一个单词全部小写，后面的单词首字母大写）
    channelId: {
      type: Number, // 数值类型
      required: true, // 必填项
    },
  },
  data() {
    return {
      artList: [],
      timestamp: Date.now(),
      loading: false,
      finished: false,
      isLoading: false,
    };
  },
  methods: {
    async initArtList(isRefresh) {
      // 请求 API 接口

      const { data: res } = await getArtListAPI(this.channelId, this.timestamp);

      if (res.message === "OK") {
        // 为时间戳重新赋值
        this.timestamp = res.data.pre_timestamp;
        // 判断是否为下拉刷新
        if (isRefresh) {
          // 下拉刷新
          // 1. “新数据”在前，“旧数据”在后
          this.artlist = [...res.data.results, ...this.artlist];
          // 2. 重置 isLoading 为 false
          this.isLoading = false;
        } else {
          // 上拉加载
          // 1. “旧数据”在前，“新数据”在后
          this.artlist = [...this.artlist, ...res.data.results];
          // 2. 重置 loading 为 false
          this.loading = false;
        }

        // 3. 判断所有的数据是否已加载完毕
        if (res.data.pre_timestamp === null) {
          this.finished = true;
        }
      }
    },
    onLoad() {
      console.log("触发了上拉加载更多");
      this.initArtList();
    },
    onRefresh() {
      console.log("触发了下拉刷新");
      this.initArtList(true);
    },
    removeArticle(id) {
    // 对原数组进行 filter 方法的过滤
    this.artlist = this.artlist.filter(item => item.art_id.toString() !== id)
 }
  },
  created() {
    this.initArtList();
  },
  components: {
    ArtItem,
  },
};
</script>

<style>
</style>